package ws.performancetest.tests.synchronization.lock;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Implementation of the shared memory using monitors.
 *
 * @author Wilson Santos, 36228 <wilson.santos@ua.pt>
 */
public class SyncImpl extends AbstractSharedListImpl {

  public synchronized void add() {
    assert invariant();
    
    /* If there's no space, wait. */
    try {
      while (list == MAX_SIZE) {
        wait();
      }
    } catch (InterruptedException ex) {
      Logger.getLogger(SyncImpl.class.getName()).log(Level.SEVERE,
              "Interrupted while waiting for space.", ex);
    }
    /* Add one element. */
    this.list++;
    notifyAll();
    
    assert invariant();
  }

  public synchronized void remove() {
    assert invariant();

    /* If there's no elements, wait. */
    try {
      while (list == 0) {
        wait();
      }
    } catch (InterruptedException ex) {
      Logger.getLogger(SyncImpl.class.getName()).log(Level.SEVERE,
              "Interrupted while waiting for elements.", ex);
    }
    /* Remove one element. */
    this.list--;
    notifyAll();

    assert invariant();
  }

  public synchronized void read() {
  }

  public synchronized void write() {
  }
}
